# -*- coding: utf-8 -*-
"""
Created on Sun Nov 12 10:53:22 2017

@author: mynumber
"""

import pandas as pd
# Fraction 可以用来表示分数
from fractions import Fraction
# 计算条件概率的乘积
def fin_data1(data,x,y):
    column = data.columns
    column = column[0:len(column)-1]
    data_y = data[data['y'].isin([y])]
    p = 1
    xi = 0
    for word in column:
        x_set = x[xi]
        xi += 1
        data_y_x = data_y[data_y[word].isin([x_set])]          #统计有多少满足条件的数据
        p = p*Fraction(len(data_y_x),len(data_y))              #计算条件概率
    return p

# 计算先验概率
def fin_data2(data, y):
    return Fraction(len(data[data['y'].isin([y])]), len(data))

def answer(data,x):
    y_data=data['y'].unique()
    P=[]
    for i in y_data:
        p1 = fin_data2(data,i)*fin_data1(data,x,i)             #分别计算x被分到所有类别的概率
        P.append(p1)
        print('    y取%d时的概率为%s' %(i, P[i]))
    p_max = max(P)
    dx = P.index(p_max)
    print('概率最大值是：%s,对应的y值为%d'%(p_max,y_data[dx]))

# 先验知识，使用DataFrame进行存储
data_dict = {'x1': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3],
            'x2': ['S', 'M', 'M', 'S', 'S', 'S', 'M', 'M', 'L', 'L', 'L', 'M', 'M', 'L', 'L'],
             'y': [-1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1]}
data=pd.DataFrame(data_dict)

#测试数据
x = (2, 'S')
print('when input is ',x)
print('The answer are :')
answer(data, x)